export class EventManager{
    //单例
    public static readonly instance = new EventManager();
    //构造函数
    private EventManager() {};
    
    private events:any = {};

    registerEvent = function(eventName:any,handler:any,scope:any){
        if(!eventName || eventName === undefined){
            console.log('event listen err: eventName is undefined!');
            return;
        }
        if(!handler || handler === undefined){
            console.log('event listen err: eventName: ' + eventName + ' & handler is undefine!');
            return;
        }
        this.events[eventName] = this.events[eventName] || [];
        this.events[eventName].push({
            scope : scope || this,
            handler : handler
        });
        return handler;
    }

    removeEvent = function(eventName:any,handler:any,scope:any){
        if (!eventName || eventName === undefined) {
            console.log('event ignore err: eventName is undefined!');
            return;
        }
        if (!handler || handler === undefined) {
            console.log('event ignore err: eventName: ' + eventName + ' & handler is undefined!');
            return;
        };
        scope = scope || this;
        let fns:any[] = this.events[eventName];
        if(!fns){return;}
        this.events[eventName] = fns.filter(function(fn:any){
            if( fn !== undefined){
                return fn.scope!=scope || fn.handler!=handler;
            }
        });
    }

    triggerEvent = function(eventName:any,params:any){
        if (!eventName || eventName === undefined) {
            console.log('event trigger err: eventName is undefined!');
            return;
        }
        // console.log("trigger event: " + eventName);
        let fns:any[] = this.events[eventName];
        if(!fns){return;}
        let ___additional = {name : eventName};
        let args = Array.prototype.slice.call(arguments,1);
        args.push(___additional);
        let fn:any = undefined;
        for(let i = 0;fn = fns[i];++i){
            if( fn !== undefined){
                fn.handler.apply(fn.scope,args);
            }
        }
    }

    getObjCount(eventName:any):number{
        this.events[eventName] = this.events[eventName] || [];
        return this.events[eventName].length;
    }

    removeEventByScope(scope){
        for(let msg in this.events){
            let obj = this.events[msg];
            if(obj){
                this.events[msg] = obj.filter(function(fn){
                    if(fn.scope != scope){
                        return true;
                    }else{
                        return false;
                    }
                })
            }
        }
    }
    
    cleanAll():void{
        this.events = {};
    }

}